package com.ljs.spring_fastdfs.config.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Slf4j
public class UploadAndDownloadUtil {
    /**
     * 单文件上传
     * @param file
     * @param filePath
     * @return
     */
    //读取配置文件自定义的路径
    @Value("${myfile.staticAccessPath}")
    String staticAccessPath;
    @Value("${myfile.uploadFolder}")
    String uploadFolder;
    public static String upload( MultipartFile file,String filePath)  {

        JsonResult jsonResult = new JsonResult();
        String finaname="";
        System.out.println("要上传的路径");
        //判断是不是空
        if (file.isEmpty()) {
            jsonResult.setMsg("文件为空");
            log.info("是空");

        } else if (file.getSize() > 10 * 1024 * 1024) {
            jsonResult.setMsg("文件太大，请上传10mb内的图片");
        } else {
            // String filePath = "E:/images/"; // 上传到本地的路径 ,要加mvc的拦截器才能访问到物理路径的图片
            String filename = file.getOriginalFilename();//文件名
            System.out.println("文件名" + filename);
            String sufix = filename.substring(filename.lastIndexOf('.'));
            System.out.println("后缀是" + sufix);
            if (sufix.equals(".jpg") || sufix.equals(".jpeg") || sufix.equals(".png") || sufix.equals(".gif")) {
                filename = UUID.randomUUID() + sufix;

                File file1 = new File(filePath + filename);//这里用自己配置的路径
                if (!file1.getParentFile().exists()) {//如果父文件不存在
                    log.info("不存在");
                    file1.getParentFile().mkdir();//创建父文件
                }

                try {
                    file.transferTo(file1);//上传
                } catch (Exception e) {
                    e.printStackTrace();
                }
                finaname = "/img/" + filename;//传入前端的名称

                System.out.println("最后的路径" + finaname);



            }else {
                log.error("格式不对");
                jsonResult.setMsg("图片格式不对");
            }

        }
        return finaname;
    }
    //多文件上传
    public static List<String> uploads(MultipartFile imgs[],String path ){
        List<String> files =new ArrayList<>();

        for(MultipartFile img:imgs ){
            if(img.getSize()>0){

                String name= img.getOriginalFilename();
                System.out.println("多文件"+name);

                //String filePath = "E:/images/"; // 上传到本地的路径 ,要加mvc的拦截器才能访问到物理路径的图片
                String sufix=  name.substring(name.lastIndexOf("."));
                name=UUID.randomUUID()+sufix;//UUID加上后缀

                File file=new File(path+name);

                if(!file.getParentFile().exists()){//如果不存在的话，就创建文件夹
                    file.getParentFile().mkdir();
                }
                try {
                    img.transferTo(file);
                    String finalname="/img/"+name;//加入虚拟路径
                    files.add(finalname);//加入显示的路径
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }

        }
        return  files;
    }

    //下载
    public static void download(String path , String filename, HttpServletResponse response) throws IOException {
        System.out.println("要下载的文件"+filename);
        // path="E:/images/";//指定路径
    filename=filename.substring(1+filename.lastIndexOf("/"));

        System.out.println("正确的文件名"+filename);
        File file=new File(path+filename);
        File file1=new File(path,filename);
        System.out.println("要下载1的存在码"+file.exists());

        System.out.println("要下载2的存在码"+file.exists());
        //设置响应头，控制浏览器下载该文件
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setContentType("application/force-download");
        response.setContentLength((int) file.length());
        FileInputStream in=new FileInputStream(file);

        OutputStream outputStream = response.getOutputStream();



        //循环将输入流中的内容读取到缓冲区当中?
        byte  b[]=new byte [1024];
        int size=0;
        size=in.read(b);
        int count=0;
        while (size!=-1){
            System.out.println(size);
            outputStream.write(b,0,size);//写入目标文件
            size=in.read(b);//size是变量，放在循环中才有效
//            System.out.println("正在拷贝。。。"+(count++));
        }

        in.close();
        outputStream.flush();


        outputStream.close();

    }



}
